import { history } from '@umijs/max';
import { message } from 'antd';
function requestInterceptor(url, options) {
  const headers = options.headers || {};
  const token = localStorage.getItem('token')
    ? { Authorization: `Bearer ${localStorage.getItem('token')}` }
    : {};

  return {
    // url,
    url: `/v1/${url}`,
    options: {
      ...options,
      headers: {
        ...headers,
        ...token,
      },
    },
  };
}

const responseInterceptors = async (res) => {
  if (res.status >= 200 && res.status < 400) {
    // 处理http状态码正确的情况
    // const res = await response.json();

    const { code, data, msg } = res.data;

    if (code !== 0) {
      if (code === 401) {
        message.error('身份过期，请重新登录').then(() => {
          localStorage.clear();
        });
        history.push('/login');
        return;
      }
      message.error(msg);
      return res;
    } else {
      return res;
    }
  } else {
    return res;
  }
};

export const requestConfig = {
  timeout: 6000,
  requestInterceptors: [requestInterceptor],
  responseInterceptors: [responseInterceptors],
};

// export const queryTable = (apiRequest) => {
//   return function (params) {
//     const { current, pageSize, ...leftProps } = params;
//     return apiRequest({
//       limit: pageSize,
//       page: current,
//       ...leftProps,
//     });
//   };
// };
